package info.emamian.droplet.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;

public class DynamoDbClientFactory {
	private static final Logger logger = LoggerFactory.getLogger(DynamoDbClientFactory.class);

	private static int clientCount = 0;
	private static int mapperCount = 0;
	private static ClasspathPropertiesFileCredentialsProvider credentialsProvider = new ClasspathPropertiesFileCredentialsProvider(
			"AwsCredentials.properties");

	public static AmazonDynamoDBClient getClientInstance() {
		AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentialsProvider);
		logger.info(client.getServiceName());

		// local or actual region
		// client.setEndpoint("http://localhost:8000", "dynamodb", "local");
		client.setRegion(Region.getRegion(Regions.US_WEST_2));

		clientCount++;
		logger.info("Client created, count:{}", clientCount);
		logger.info("Listing tables: " + client.listTables());
		return client;
	}

	/**
	 * Creates a mapper ( and a client for it) and returns the usable mapper.
	 * 
	 * @return
	 */
	public static DynamoDBMapper getMapperInstance() {
		DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(DynamoDBMapperConfig.SaveBehavior.CLOBBER,
				DynamoDBMapperConfig.ConsistentReads.CONSISTENT, null, // TableNameOverride
																		// -
																		// leaving
																		// this
																		// at
																		// default
																		// setting
				DynamoDBMapperConfig.PaginationLoadingStrategy.EAGER_LOADING);

		DynamoDBMapper mapper = new DynamoDBMapper(getClientInstance(), mapperConfig, credentialsProvider);
		mapperCount++;
		if (logger.isDebugEnabled()) {
			logger.debug("Mapper created, count:{}", mapperCount);
		}
		return mapper;
	}

	public static int getClientCount() {
		return clientCount;
	}

	public static void setClientCount(int clientCount) {
		DynamoDbClientFactory.clientCount = clientCount;
	}

	public static int getMapperCount() {
		return mapperCount;
	}

	public static void setMapperCount(int mapperCount) {
		DynamoDbClientFactory.mapperCount = mapperCount;
	}

}
